﻿using ETask.Api.Models;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore;

namespace ETask.Api.Data
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }

        public DbSet<Dept> Depts { get; set; }

        public DbSet<Project> Projects {  get; set; }

        public DbSet<ProjectMember> ProjectMembers { get; set; }

        public DbSet<TaskFile> TaskFiles { get; set; }  

        public DbSet<ProjectDoc> ProjectDocs { get; set; }

        public DbSet<ProjectTask> ProjectTasks { get; set; }

        public DbSet<AuditLog> AuditLogs { get; set; }

        /// <summary>
        /// 保存更改前的操作
        /// </summary>
        public override int SaveChanges()
        {
            foreach (var entry in ChangeTracker.Entries<BaseEntity>())
            {
                switch (entry.State)
                {
                    case EntityState.Added:
                        entry.Entity.CreatedAt = DateTime.Now;
                        entry.Entity.UpdatedAt = DateTime.Now;
                        break;
                    case EntityState.Modified:
                        entry.Entity.UpdatedAt = DateTime.Now;
                        entry.Property(x => x.CreatedAt).IsModified = false;
                        break;
                }
            }

            return base.SaveChanges();
        }
    }
}
